package com.example.aoporder.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Random;

@Aspect
@Component
public class OrderServiceAspect {

    private final Random random = new Random();

    /* 1. 前置增强 */
    @Before("execution(* com.example.aoporder.service.OrderService.*(..))")
    public void before() {
        System.out.println("hello, 我是一个前置增强");
    }

    /* 2. 后置增强（add/delete 返回后） */
    @After("execution(* com.example.aoporder.service.OrderService.add(..)) || " +
            "execution(* com.example.aoporder.service.OrderService.delete(..))")
    public void after() {
        System.out.println("bye, 我是一个后置增强");
    }

    /* 3. 返回后增强（可拿到返回值） */
    @AfterReturning(pointcut = "execution(* com.example.aoporder.service.OrderService.*(..))",
            returning = "result")
    public void afterReturning(Object result) {
        System.out.println("方法返回值为: " + result);
    }

    /* 4. 环绕增强（统计耗时） */
    @Around("execution(* com.example.aoporder.service.OrderService.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object obj = pjp.proceed();
        long cost = System.currentTimeMillis() - start;
        System.out.println("方法执行耗时: " + cost + " ms");
        return obj;
    }

    /* 5. 权限校验（add/delete 前） */
    @Before("execution(* com.example.aoporder.service.OrderService.add(..)) || " +
            "execution(* com.example.aoporder.service.OrderService.delete(..))")
    public void checkAuth() {
        boolean ok = random.nextInt(2) == 0;
        if (!ok) {
            System.out.println("权限校验失败，终止调用！");
            throw new RuntimeException("NO_AUTH");
        }
        System.out.println("权限校验通过");
    }
}